package com.zhb.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * @program: upload_demo
 * @description: 文件上传工具类
 * @author: rainboz
 * @create: 2019-10-24 20:12
 **/
public class UploadFile {

    public static String upimg(MultipartFile file, HttpServletRequest request, String package1) {
        //使用原文件名
        String oldFileName = file.getOriginalFilename();
        String format = file.getContentType().split("/")[1];

        if (format.equals(Constant.PNG) || format.equals(Constant.GIF)
                || format.equals(Constant.JPEG)
                || format.equals(Constant.JPG)){
            String path = request.getSession().getServletContext().getRealPath("/upimgs/" + package1);
            String fileName = UUID.randomUUID().toString().replace("-", "").substring(1, 11) + "." + format;

            File targetFile = new File(path, oldFileName);
            System.out.println("path: " + path);
            System.out.println("format: " + format);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {

                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            return "";
        }
        return "/upimgs/" + package1 + File.separator + oldFileName;//返回相对路径
    }

    public static void deleteFile(HttpServletRequest request, String path) {
        String abPath = request.getServletPath() + path;
        File f = new File(abPath);
        if (f.exists()) f.delete();
    }

    public static String getExtensionName(MultipartFile file) {
        // 获取原始图片的扩展名
        String originalFilename = file.getOriginalFilename();
        String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
        return extensionName;
    }
}
